import 'dart:io';

import 'package:file_selector/file_selector.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:get/get.dart';
import 'package:jar_replacer/config_controller.dart';
import 'package:jar_replacer/theme_controller.dart';
import 'package:fluentui_system_icons/fluentui_system_icons.dart' as icon;

class Setting extends StatefulWidget {
  const Setting({super.key});

  @override
  State<StatefulWidget> createState() {
    return SettingState();
  }
}

class SettingState extends State<Setting> {
  static const double rowHeight = 80;
  Directory? workspaceDir;
  final TextEditingController _workspacePathController =
      TextEditingController();

  final TextEditingController _outputDirController =
  TextEditingController();
  // 控制器引用
  late ConfigController configController;
  late ThemeController themeController;
  
  final TextEditingController _newConfigNameController = TextEditingController();
  final TextEditingController _renameConfigController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // 使用Obx包装UI，确保主题变化时能自动更新
    return Acrylic(
        // 设置应用于 Acrylic 效果的颜色。这个颜色会与底层内容混合。
        tint: Colors.white.withOpacity(0.1),
        //tintAlpha: 0.5,
        // 设置模糊的程度，数值越大，模糊效果越强。
        blurAmount: 0.0, // 设置模糊程度
        // 阴影效果
        elevation: 0,
        child:  Obx(()=>Container(
            color: themeController.isDark
                ? Colors.black.withOpacity(0.8)
                : Colors.white.withOpacity(0.5),
            child: Padding(
                padding: EdgeInsets.all(36.0),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    // 配置管理部分
                    Container(
                      padding: const EdgeInsets.all(20.0),
                      margin: const EdgeInsets.only(bottom: 10),
                      decoration: BoxDecoration(
                        color: themeController.isDark
                            ? Colors.black.withOpacity(0.5)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(10), // 圆角
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1), // 阴影颜色
                            spreadRadius: 5, // 扩展半径
                            blurRadius: 7, // 模糊半径
                            offset: Offset(0, 3), // 阴影相对于组件的偏移量
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Icon(
                                    icon.FluentIcons.settings_48_regular,
                                    size: 24.0,
                                  ),
                                  SizedBox(
                                    width: 20,
                                  ),
                                  Text("配置管理", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black)),
                                ],
                              ),
                              Row(
                                children: [
                                  Button(
                                    child: Row(
                                      children: [
                                        Icon(icon.FluentIcons.add_24_regular),
                                        SizedBox(width: 5),
                                        Text("新建配置", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black)),
                                      ],
                                    ),
                                    onPressed: () {
                                      _showCreateConfigDialog();
                                    },
                                  ),
                                  SizedBox(width: 8),
                                  Button(
                                    child: Icon(
                                      icon.FluentIcons.folder_open_24_regular,
                                      size: 20.0,
                                    ),
                                    onPressed: () {
                                      // 获取当前用户的AppData目录
                                      String userHome = Platform.environment['USERPROFILE'] ?? '';
                                      String configDir = '$userHome\\AppData\\Roaming\\com.example\\jar_replacer';
                                      
                                      // 创建目录（如果不存在）
                                      Directory(configDir).createSync(recursive: true);
                                      
                                      // 打开目录
                                      Process.run('explorer', [configDir]);
                                    },
                                  ),
                                ],
                              ),
                            ],
                          ),
                          SizedBox(height: 15),
                          // 配置列表
                          SizedBox(
                            height: 200,
                            child: ListView.builder(
                              itemCount: configController.configurations.length,
                              itemBuilder: (context, index) {
                                final config = configController.configurations[index];
                                final isActive = config.name == configController.activeConfigName;

                                return Card(
                                  backgroundColor: isActive
                                      ? (themeController.isDark ? Colors.blue.dark : Colors.blue.light)
                                      : null,
                                  margin: EdgeInsets.symmetric(vertical: 5),
                                  child: ListTile(
                                    title: Text(
                                      config.name,
                                      style: isActive ? TextStyle(fontWeight: FontWeight.bold) : null,
                                    ),
                                    subtitle: Text('工作空间: ${config.workspaceDir}'),
                                    trailing: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        IconButton(
                                          icon: Icon(icon.FluentIcons.edit_24_regular),
                                          onPressed: () {
                                            _showRenameConfigDialog(config.name);
                                          },
                                        ),
                                        IconButton(
                                          icon: Icon(icon.FluentIcons.delete_24_regular),
                                          // 通过设置onPressed为null来禁用按钮
                                          onPressed: isActive ? null : () {
                                            _showDeleteConfigDialog(config.name);
                                          },
                                          style: ButtonStyle(
                                            foregroundColor: WidgetStateProperty.all(Colors.red),
                                          ),
                                        ),
                                      ],
                                    ),
                                    onPressed: () {
                                      if (!isActive) {
                                        // switchConfiguration返回void，不使用其结果
                                        configController.switchConfiguration(config.name);
                                        setState(() {
                                          // 更新文本框的值
                                          _workspacePathController.text = config.workspaceDir ?? '';
                                          _outputDirController.text = config.outputDir ?? '';
                                        });
                                      }
                                    },
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      height: rowHeight,
                      padding: const EdgeInsets.all(20.0),
                      decoration: BoxDecoration(
                        color: themeController.isDark
                            ? Colors.black.withOpacity(0.5)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(10), // 圆角
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1), // 阴影颜色
                            spreadRadius: 5, // 扩展半径
                            blurRadius: 7, // 模糊半径
                            offset: Offset(0, 3), // 阴影相对于组件的偏移量
                          ),
                        ],
                      ),
                      child: Row(
                        children: [
                          Icon(
                            icon.FluentIcons.cloud_48_regular,
                            size: 24.0,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          SizedBox(
                            width: 88,
                            child: Text("工作空间", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black)),
                          ),
                          Expanded(
                            child: TextBox(
                              controller: _workspacePathController,
                              readOnly: true,
                            ),
                          ),
                          SizedBox(width: 8),
                          IconButton(
                              icon: Icon(
                                icon.FluentIcons.folder_48_regular,
                                size: 24.0,
                              ),
                              onPressed: () {
                                selectWorkspaceDir(context);
                              }),
                          SizedBox(width: 8),
                          IconButton(
                              icon: Icon(
                                icon.FluentIcons.folder_open_24_regular,
                                size: 24.0,
                              ),
                              onPressed: () {
                                if (_workspacePathController.text.isNotEmpty) {
                                  Process.run('explorer', [_workspacePathController.text]);
                                }
                              }),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                      height: rowHeight,
                      padding: const EdgeInsets.all(20.0),
                      decoration: BoxDecoration(
                        color: themeController.isDark
                            ? Colors.black.withOpacity(0.5)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(10), // 圆角
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1), // 阴影颜色
                            spreadRadius: 5, // 扩展半径
                            blurRadius: 7, // 模糊半径
                            offset: Offset(0, 3), // 阴影相对于组件的偏移量
                          ),
                        ],
                      ),
                      child: Row(
                        children: [
                          Icon(
                            icon.FluentIcons.arrow_export_up_24_regular,
                            size: 24.0,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          SizedBox(
                            width: 88,
                            child: Text("输出目录", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black)),
                          ),
                          Expanded(
                            child: TextBox(
                              controller: _outputDirController,
                              readOnly: true,
                            ),
                          ),
                          SizedBox(width: 8),
                          IconButton(
                              icon: Icon(
                                icon.FluentIcons.folder_48_regular,
                                size: 24.0,
                              ),
                              onPressed: () {
                                selectOutputDir(context);
                              }),
                          SizedBox(width: 8),
                          IconButton(
                              icon: Icon(
                                icon.FluentIcons.folder_open_24_regular,
                                size: 24.0,
                              ),
                              onPressed: () {
                                if (_outputDirController.text.isNotEmpty) {
                                  Process.run('explorer', [_outputDirController.text]);
                                }
                              }),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                      height: rowHeight,
                      padding: EdgeInsets.all(20.0),
                      decoration: BoxDecoration(
                        color: themeController.isDark
                            ? Colors.black.withOpacity(0.5)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(10), // 圆角
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1), // 阴影颜色
                            spreadRadius: 5, // 扩展半径
                            blurRadius: 7, // 模糊半径
                            offset: Offset(0, 3), // 阴影相对于组件的偏移量
                          ),
                        ],
                      ),
                      child: Row(
                        children: [
                          Icon(
                            !themeController.isDark
                                ? icon.FluentIcons.lightbulb_48_regular
                                : icon.FluentIcons.lightbulb_48_filled,
                            size: 24.0,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          SizedBox(
                            width: 88,
                            child: Text(themeController.isDark ? "暗黑模式" : "明亮模式", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black)),
                          ),
                          Expanded(child: Text('')),
                          ToggleSwitch(
                            checked: themeController.isDark,
                            onChanged: (bool value) {
                              themeController.toggleTheme();
                            },
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                      height: rowHeight,
                      decoration: BoxDecoration(
                        color: themeController.isDark
                            ? Colors.black.withOpacity(0.5)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(10), // 圆角
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1), // 阴影颜色
                            spreadRadius: 5, // 扩展半径
                            blurRadius: 7, // 模糊半径
                            offset: Offset(0, 3), // 阴影相对于组件的偏移量
                          ),
                        ],
                      ),
                      padding: const EdgeInsets.all(20.0),
                      child: Row(
                        children: [
                          Icon(
                            icon.FluentIcons.color_24_regular,
                            size: 24.0,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          SizedBox(
                            width: 88,
                            child: Text("强调色", style: TextStyle(color: themeController.isDark?Colors.white: Colors.black),),
                          ),
                          Expanded(child: Text('')),
                          SplitButton(
                            flyout: FlyoutContent(
                              constraints: BoxConstraints(maxWidth: 200.0),
                              child: Wrap(
                                runSpacing: 10.0,
                                spacing: 8.0,
                                children: Colors.accentColors.map((color) {
                                  return Obx(() => Button(
                                    autofocus: themeController.color == color,
                                    style: ButtonStyle(
                                      padding: WidgetStatePropertyAll(
                                        EdgeInsets.all(4.0),
                                      ),
                                      // 设置透明背景
                                      backgroundColor: WidgetStatePropertyAll(
                                        Colors.transparent,
                                      ),
                                    ),
                                    onPressed: () {
                                      themeController.setThemeColor(color);
                                      configController.setThemeColor(color);
                                      Navigator.of(context).pop(color);
                                    },
                                    child: Container(
                                      height: 32,
                                      width: 32,
                                      decoration: BoxDecoration(
                                        color: color,
                                        // 在暗黑模式下添加白色边框以增强可见性
                                        border: themeController.isDark ? Border.all(
                                          color: Colors.white.withOpacity(0.5),
                                          width: 1.0,
                                        ) : null,
                                      ),
                                    ),
                                  ));
                                }).toList(),
                              ),
                            ),
                            child: Obx(() => Container(
                              decoration: BoxDecoration(
                                color: themeController.color,
                                borderRadius:
                                const BorderRadiusDirectional.horizontal(
                                  start: Radius.circular(4.0),
                                ),
                              ),
                              height: 32,
                              width: 36,
                            )),
                          )
                        ],
                      ),
                    )
                  ],
                )))));
    //
  }

  @override
  void initState() {
    super.initState();
    
    // 初始化控制器引用
    configController = Get.find<ConfigController>();
    themeController = Get.find<ThemeController>();
    
    // 初始化控制器的值
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _workspacePathController.text = configController.currentConfig?.value?.workspaceDir ?? '';
      _outputDirController.text = configController.currentConfig?.value?.outputDir ?? '';
      workspaceDir = Directory(configController.currentConfig?.value?.workspaceDir ?? '');
    });
  }

  Future<void> selectWorkspaceDir(BuildContext context) async {
    final String? result = await getDirectoryPath();
    // themeController已在build方法中获取
    if (result != null) {
      setState(() {
        workspaceDir = Directory(result);
        _workspacePathController.text = result;
      });
      configController.setWorkspaceDir(result);
    }
  }

  Future<void> selectOutputDir(BuildContext context) async {
    final String? result = await getDirectoryPath();
    // themeController已在build方法中获取
    if (result != null) {
      setState(() {
        // workspaceDir = Directory(result);
        _outputDirController.text = result;
      });
      configController.setOutputDir(result);
    }
  }

  // 显示新建配置对话框
  void _showCreateConfigDialog() async {
    _newConfigNameController.clear();
    
    await showDialog(
      context: context,
      builder: (context) {
        return ContentDialog(
          title: Text("新建配置"),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text("请输入配置名称:"),
              SizedBox(height: 10),
              TextBox(
                controller: _newConfigNameController,
                placeholder: "配置名称",
              ),
            ],
          ),
          actions: [
            Button(
              child: Text("取消"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            Button(
              child: Text("确定"),
              onPressed: () async {
                final name = _newConfigNameController.text.trim();
                if (name.isNotEmpty && !configController.configurations.any((c) => c.name == name)) {
                  configController.createConfiguration(name, {
                    'workspaceDir': workspaceDir?.path ?? '',
                    'outputDir': _outputDirController.text,
                  });
                  setState(() {});
                  Navigator.pop(context);
                } else {
                  await showDialog(
                    context: context,
                    builder: (context) => ContentDialog(
                      title: Text("错误"),
                      content: Text("配置名称不能为空或已存在"),
                      actions: [
                        Button(
                          child: Text("确定"),
                          onPressed: () => Navigator.pop(context),
                        ),
                      ],
                    ),
                  );
                }
              },
            ),
          ],
        );
      },
    );
  }

  // 显示重命名配置对话框
  void _showRenameConfigDialog(String configName) async {
    _renameConfigController.text = configName;
    
    await showDialog(
      context: context,
      builder: (context) {
        return ContentDialog(
          title: Text("重命名配置"),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text("请输入新的配置名称:"),
              SizedBox(height: 10),
              TextBox(
                controller: _renameConfigController,
                placeholder: "配置名称",
              ),
            ],
          ),
          actions: [
            Button(
              child: Text("取消"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            Button(
              child: Text("确定"),
              onPressed: () async {
                final newName = _renameConfigController.text.trim();
                if (newName.isNotEmpty && !configController.configurations.any((c) => c.name == newName)) {
                    configController.renameConfiguration(configName, newName);
                  setState(() {});
                  Navigator.pop(context);
                } else {
                  await showDialog(
                    context: context,
                    builder: (context) => ContentDialog(
                      title: Text("错误"),
                      content: Text("配置名称不能为空或已存在"),
                      actions: [
                        Button(
                          child: Text("确定"),
                          onPressed: () => Navigator.pop(context),
                        ),
                      ],
                    ),
                  );
                }
              },
            ),
          ],
        );
      },
    );
  }

  // 显示删除配置对话框
  void _showDeleteConfigDialog(String configName) async {
    
    await showDialog(
      context: context,
      builder: (context) {
        return ContentDialog(
          title: Text("删除配置"),
          content: Text("确定要删除配置 '$configName' 吗？"),
          actions: [
            Button(
              child: Text("取消"),
              onPressed: () => Navigator.pop(context),
            ),
            Button(
              child: Text("删除"),
              style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(Colors.red.light),
                foregroundColor: WidgetStateProperty.all(Colors.white),
              ),
              onPressed: () async {
                configController.deleteConfiguration(configName);
                setState(() {});
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }
}
